//
//  CreateSendOrderController.m
//  FactorySale
//
//  Created by 主事丫环HU on 2020/7/28.
//  Copyright © 2020 主事丫环. All rights reserved.
//
/**
 分三个区，第一个区展示列表，第二个和第三个区都只有一个cell
 */

#import "CreateSendOrderController.h"
#import "CreateSendOrderCell.h"// 发货清单列表cell
#import "CreateSendOrderHeaderView.h"// 区头
#import "AddProductAndTotalMoneyCell.h"// 添加商品计算总金额cell
#import "OrderInfonCell.h"// 底部订单信息cell
#import "SelectProductModel.h"// 选择的合作产品model
#import "OrderInfoModel.h"// 底部订单信息的model，用来给OrderInfonCell赋值，否则会出现按钮刷新重置的bug
#import "MyClientController.h"
#import "RepeatSelectProductController.h"
#define NibWithClass(Class)  [UINib nibWithNibName:NSStringFromClass([Class class]) bundle:nil]
#define StringWithClass(Class) NSStringFromClass([Class class])
@interface CreateSendOrderController ()
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topNavBarConstraint;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSString *totalMoney;
@property (nonatomic,strong) OrderInfoModel *infoModel;

@property (nonatomic, strong) NSString *userToken;
@end

@implementation CreateSendOrderController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.topNavBarConstraint.constant = kNaviHeight;
    
    // 给发货清单设置初始数量
    for (int i = 0; i< self.modelArray.count; i++) {
        SelectProductListModel *model = self.modelArray[i];
        model.quantity = @"1";
    }
    self.totalMoney = @"0.00";
    // 初始化底部信息model
    self.infoModel = [[OrderInfoModel alloc] init];
    self.infoModel.isPay = NO;
    self.infoModel.orderNumber = @"";
    self.infoModel.companyName = @"";
    // 计算并刷新UI
    [self calculateTheTotalMoneyAndRefreshUI];
    [self setupUI];
    // 获取userToken 这个参数是为了防止安卓出现重复点击的情况
    self.userToken = @"";
    [self requestUserToken];
}
- (void)requestUserToken{
    [NetWorkTool POST:getUserToken param:nil success:^(id dic) {
        self.userToken = dic[@"data"];
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}
- (void)setupUI{
    
    self.nameLabel.text = self.model.name;
    self.phoneLabel.text = self.model.phone;
    self.addressLabel.text = self.model.address;
    self.view.backgroundColor = Main_BackGroundColor;
    [self.tableView registerNib:NibWithClass(CreateSendOrderHeaderView) forHeaderFooterViewReuseIdentifier:StringWithClass(CreateSendOrderHeaderView)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
}
#pragma mark - tableview delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    } else if (indexPath.section == 1) {
        return 90;
    } else {
        return 260;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 50;
    } else {
        return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    CreateSendOrderHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:StringWithClass(CreateSendOrderHeaderView)];
    
    return headerView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView = [[UIView alloc] init];
    return footerView;
}
#pragma mark - tableview datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (section == 0) {
        return self.modelArray.count;
    } else {
        return 1;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        SelectProductListModel *model = self.modelArray[indexPath.row];
        CreateSendOrderCell *cell = [CreateSendOrderCell cellWithTableView:tableView];
        cell.faHuoNumTFEndHandle = ^(NSString * _Nonnull text) {
            
            model.quantity = text;
            [self calculateTheTotalMoneyAndRefreshUI];
        };
        cell.priceChangedEndHandle = ^(NSString * _Nonnull text) {
            model.price = text.doubleValue;
            [self calculateTheTotalMoneyAndRefreshUI];
        };
        [cell.deleteButton addTarget:self action:@selector(deleteButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.deleteButton.tag = indexPath.row;
        cell.model = model;
        return cell;
    } else if (indexPath.section == 1){
        AddProductAndTotalMoneyCell *cell = [AddProductAndTotalMoneyCell cellWithTableView:tableView];
        [cell.addProductButton addTarget:self action:@selector(addProductButtonClick) forControlEvents:UIControlEventTouchUpInside];
        cell.totalMoneyLabel.text = [NSString stringWithFormat:@"¥%@",self.totalMoney];
        return cell;
    } else {
        
        OrderInfonCell * cell = [OrderInfonCell cellWithTableView:tableView];
        cell.payStatusChangedClick = ^(BOOL isPay) {
            self.infoModel.isPay = isPay;
        };
        cell.orderNumberTextChangedClick = ^(NSString * _Nonnull orderNumber) {
            self.infoModel.orderNumber = orderNumber;
        };
        cell.companyTextChangedClick = ^(NSString * _Nonnull companyName) {
            self.infoModel.companyName = companyName;
        };
        cell.model = self.infoModel;
        [cell.confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}
- (void)deleteButtonClick:(UIButton *)sender{
    SelectProductListModel *model = self.modelArray[sender.tag];
    [self.modelArray removeObject:model];
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
    [self calculateTheTotalMoneyAndRefreshUI];
}
- (void)calculateTheTotalMoneyAndRefreshUI{
    
    NSMutableArray *singleTotalMoneyArray = [NSMutableArray arrayWithCapacity:0];
    for (SelectProductListModel *model in self.modelArray) {
        NSString *sale = [NSString stringWithFormat:@"%.2f",model.price];
        NSString * quantity;
        if ([model.quantity isEqualToString:@""]) {
            quantity = @"0";
        } else {
            quantity = model.quantity;
        }
        NSDecimalNumber *count = [NSDecimalNumber decimalNumberWithString:quantity];
        NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithString:sale];        NSDecimalNumber *singleTotalMoney = [count decimalNumberByMultiplyingBy:price];
        [singleTotalMoneyArray addObject:singleTotalMoney];
    }
    
    NSDecimalNumber *sum = [singleTotalMoneyArray valueForKeyPath:@"@sum.self"];
    self.totalMoney = [NSString stringWithFormat:@"%.2f",[sum doubleValue]];
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:1];
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
}
- (void)confirmButtonClick{
    NSMutableArray *attributesArray = [NSMutableArray array];
    NSMutableArray *countsArray = [NSMutableArray array];
    NSMutableArray *priceArray = [NSMutableArray array];
    NSMutableArray *partsIdArray = [NSMutableArray array];
    if (self.modelArray.count == 0) {
        ShowToastWithText(@"请添加商品");
        return;
    }
    for (SelectProductListModel *model in self.modelArray) {
        
        [attributesArray addObject:model.attribute];
        [countsArray addObject:model.quantity];
        [partsIdArray addObject:model.partsId];
        [priceArray addObject:[NSString stringWithFormat:@"%.2f",model.price]];
        
        if ([model.quantity intValue] ==0) {
            ShowToastWithText(@"发货数量不能为0");
            return;
        }
        if ([model.quantity isEqualToString:@""]) {
            ShowToastWithText(@"发货数量不能为空");
            return;
        }
        if (model.price == 0) {
            ShowToastWithText(@"单价不能为空或0");
            return;
        }
    };
    
    self.infoModel.orderNumber = [self filterSpaces:self.infoModel.orderNumber];
    self.infoModel.orderNumber = [self disable_emoji:self.infoModel.orderNumber];
    
    self.infoModel.companyName = [self filterSpaces:self.infoModel.companyName];
    self.infoModel.companyName = [self disable_emoji:self.infoModel.companyName];
    
    NSString *attributes = [attributesArray componentsJoinedByString:@","];
    NSString *counts = [countsArray componentsJoinedByString:@","];
    NSString *partsIds = [partsIdArray componentsJoinedByString:@","];
    NSString *prices = [priceArray componentsJoinedByString:@","];
    NSString *isPay = [NSString stringWithFormat:@"%d",self.infoModel.isPay];

    NSDictionary *param = @{
        @"attributes":NOTNIL(attributes),
        @"counts":NOTNIL(counts),
        @"salePrice":NOTNIL(prices),
        @"amount":NOTNIL(self.totalMoney),
        @"isPay":NOTNIL(isPay),
        @"logistics_num":NOTNIL(self.infoModel.orderNumber),
        @"logistics_name":NOTNIL(self.infoModel.companyName),
        @"partsIds":NOTNIL(partsIds),
        @"userToken":NOTNIL(self.userToken),
        @"factoryUserId":NOTNIL(self.model.id)
    };
    [MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    [NetWorkTool POST:createUserSnedOrder param:param success:^(id dic) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[MyClientController class]]) {
                  [self.navigationController popToViewController:vc animated:YES];
                  return;
            }
        }
        
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:YES];
}
- (void)addProductButtonClick{
    RepeatSelectProductController * vc = [[RepeatSelectProductController alloc] init];
    NSMutableArray *attributesArray = [NSMutableArray array];
    for (SelectProductListModel *model in self.modelArray) {
        [attributesArray addObject:model.attribute];
    }
    NSString *attributes = [attributesArray componentsJoinedByString:@","];
    vc.attributes = attributes;
    vc.SelectProductModelArrayClick = ^(NSMutableArray * _Nonnull selectArray) {
        for (int i = 0; i< selectArray.count; i++) {
            SelectProductListModel *model = selectArray[i];
            model.quantity = @"1";
        }
        [self.modelArray addObjectsFromArray:selectArray];
        NSIndexSet *set = [NSIndexSet indexSetWithIndex:0];
        [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
        [self calculateTheTotalMoneyAndRefreshUI];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
// 过滤空格
- (NSString *)filterSpaces:(NSString *)text{
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"\n"withString:@""];
    return text;
}
/**
 *  过滤字符串中的emoji
 */
- (NSString *)disable_emoji:(NSString *)text{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text
                                                               options:0
                                                                 range:NSMakeRange(0, [text length])
                                                          withTemplate:@""];
    return modifiedString;
}
@end
